<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\captcha\Captcha;

/**
 * Login form
 */
class LoginForm extends Model
{
    public $user_name;
    public $password;
    public $rememberMe = TRUE;

    private $_user;

    /**
     * @inheritdoc
     */
    public function rules ()
    {
        return [
            // mob_phone and password are both required
            [ [ 'user_name' , 'password' ] , 'required' ] ,
            // rememberMe must be a boolean value
            [ 'rememberMe' , 'boolean' ] ,
            // password is validated by validatePassword()
            [ 'password' , 'validatePassword' ] ,
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array  $params the additional name-value pairs given in the rule
     */
    public function validatePassword ( $attribute , $params )
    {
        if ( !$this->hasErrors() ) {
            $loginAuth = $this->getAuth();
            $user = $this->getUser();

            if ( strlen($this->password)<4 || !$user || !$user->validatePassword( $this->password ) || $loginAuth['is_pc'] == 2 ||  $loginAuth['status'] == 9 ) {
                $this->addError( $attribute , '用户名或密码错误' );
            }
        }
    }

    /**
     * Logs in a user using the provided mob_phone and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login ( $time )
    {
        if ( $this->validate() ) {
            return Yii::$app->user->login( $this->getUser() , $this->rememberMe ? $time : 0 );
        } else {
            return FALSE;
        }
    }

    //获取登录权限
    public function getAuth ()
    {
        if($this->user_name){
            $is_pc = AdminUser::find()->select('is_pc,status')->where(array('username'=>$this->user_name))->one();
        }
        return $is_pc;
    }


    /**
     * Finds user by [[mob_phone]]
     *
     * @return AdminUser|null
     */
    protected function getUser ()
    {
        if ( $this->_user === NULL ) {
            $this->_user = AdminUser::findByUserName( $this->user_name );
        }

        return $this->_user;
    }

    public function attributeLabels ()
    {
        return [
            'user_name' => '用户名' ,
            'password'  => '密码' ,
        ];
    }
}
